<?php

namespace app\admin\framework\controller;

use app\admin\framework\api\Permission;
use app\admin\framework\validate\UserValidate;
use app\common\model\Dept;
use app\common\model\Role;
use app\common\model\RoleUser;
use app\common\model\User;
use app\common\model\UserDeptAuth;
use app\common\service\UserService;

#[Permission('管理员管理', 'Auth')]
class AdminController
{
    private $model;
    
    public function __construct()
    {
        $this->model = new User();
    }
    
    #[Permission('参数')]
    public function option()
    {
        return apiSuccess(data: [
            'roles' => Role::where('status', 1)->select()->toArray(),
            'depts' => Dept::where('status', 1)->select()->toArray()
        ]);
    }
    
    #[Permission('详情')]
    public function detail()
    {
        $id = request()->get('id', 0);
        $result = $this->model->where('id', $id)->hidden(['password'])->find()->toArray();
        $result['role_id'] = RoleUser::where('user_id', $id)->column('role_id');
        return apiSuccess(data: $result);
    }
    
    #[Permission('查询')]
    public function select()
    {
        $keyword = request()->get('keyword', '');
        $dept_id = request()->get('dept_id', 0);
        $result = $this->model->where('user_type', 1);
        if($keyword != ''){
            $result =  $result->where('nickname|mobile','like','%'.$keyword.'%');
        }
        if($dept_id != 0){
            $result =  $result->where('dept_id',$dept_id);
        }
        $result = $result->order('id asc')->paginate();
        return apiSuccess(data: ['list' => $result->items(), 'total' => $result->total()]);
    }
    
    #[Permission('创建')]
    public function create()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            $validate = new UserValidate();
            if (!$validate->scene('add')->check($data)) {
                return apiError($validate->getError());
            }
            if (!empty($data['password'])) {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }else{
                unset($data['password']);
            } 
            $data['user_type'] = 1;
            $roleIds = $data['role_id'];
            unset($data['role_id']);
            $userId = $this->model->insertGetId($data);
            RoleUser::insertAll(array_map(fn($item) => ['role_id' => $item, 'user_id' => $userId], $roleIds));
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }
    
    #[Permission('更新')]
    public function update()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            $validate = new UserValidate();
            if (!$validate->scene('edit')->check($data)) {
                return apiError($validate->getError());
            }
            if (!empty($data['password'])) {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }else{
                unset($data['password']);
            }
            
            RoleUser::where('user_id', $data['id'])->delete();
            RoleUser::insertAll(array_map(fn($item) => ['role_id' => $item, 'user_id' => $data['id']], $data['role_id']));
            unset($data['role_id']);
            $this->model->update($data);
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }
    
    #[Permission('快捷修改')]
    public function speed()
    {
        if (setFieldUpdate(new User())) {
            return apiSuccess('修改成功');
        } else {
            return apiError('修改失败');
        }
    }
    
    
    #[Permission('删除')]
    public function delete()
    {
        if (request()->method() === 'DELETE') {
            $id = request()->get('id', 0);
            if ($this->model->delete($id) !== false) {
                return apiSuccess('删除成功');
            } else {
                return apiError('删除失败');
            }
        }
        return apiError('删除失败');
        
    }

    #[Permission('数据权限')]
    public function getUserDeptAuth()
    {
        $data = [];
        $id = request()->get('id', 0);
        $result = UserDeptAuth::where('user_id', $id)->find();
        if ($result) {
            $result->toArray();
            if (!empty($result["dept_ids"])) {
                $dept_ids = explode(',', $result["dept_ids"]);
                for ($i=0; $i < count($dept_ids); $i++) {
                    $dept_ids[$i] = intval($dept_ids[$i]);
                }
                $result["dept_ids"] = $dept_ids;
            } else {
                $result["dept_ids"] = [];
            }
            $data = $result;
        }
        return apiSuccess(data: $data);
    }

    #[Permission('保存数据权限')]
    public function saveUserDeptAuth()
    {
        $id = request()->post('id', 0);
        $user_id = request()->post('user_id', 0);
        $title = request()->post('title', '');
        $dept_ids = request()->post('dept_ids', []);
        $dept_id = '';
        if (!empty($dept_ids)) {
            $dept_id = implode(',', $dept_ids);
        }
        $data = [
            'user_id' => $user_id,
            'title' => $title,
            'dept_ids' => $dept_id
        ];
        if ($id > 0) {
            $data["update_time"] = date("Y-m-d H:i:s");
            UserDeptAuth::where('id', $id)->update($data);
        } else {
            $data["create_time"] = date("Y-m-d H:i:s");
            UserDeptAuth::create($data);
        }
        return apiSuccess('操作成功');
    }
}